package com.unittec.drainage.sdk.root.internal.base;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import com.unittec.drainage.sdk.root.GatewayClient;
import com.unittec.drainage.sdk.root.common.FieldConstants;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.internal.utils.SdkUtils;

public abstract class AbstractGatewayClient implements GatewayClient {
    private final String serverUrl;
    private final String appId;
    private final String appKey;
    private String appSettingId;
    private String token;

    public AbstractGatewayClient(String serverUrl, String appId, String appKey, String appSettingId) {
        this.serverUrl = serverUrl;
        this.appId = appId;
        this.appKey = appKey;
        this.appSettingId = appSettingId;
    }

    public AbstractGatewayClient(String serverUrl, String appId, String appKey) {
        this.serverUrl = serverUrl;
        this.appId = appId;
        this.appKey = appKey;
    }

    private Integer getServiceNumber(GatewayRequest request) {
        // String[] names = request.getClass().getName().split("\\.");
        // String number = names[names.length - 1].replaceAll("\\D", "");
        return Integer.parseInt(request.getMethod());
    }

    @Override
    public ResponseContent execute(GatewayRequest request) {
        return this.execute(request, this.getServiceNumber(request), null);
    }

    @Override
    public ResponseContent execute(GatewayRequest request, Integer number) {
        return this.execute(request, number, null);
    }

    @Override
    public ResponseContent execute(GatewayRequest request, String token) {
        return this.execute(request, this.getServiceNumber(request), token);
    }

    @Override
    public ResponseContent execute(GatewayRequest request, Integer number, String token) {
        request.setAppId(this.appId);
        request.setAppKey(this.appKey);
        request.setAppSettingId(this.appSettingId);
        request.setTimestamp(System.currentTimeMillis());
        request.setMethod(number.toString());
        if (token != null) {
            request.setToken(token);
        } else {
            request.setToken(this.token);
        }
        request.setSign(request.createSign());
        String requestJson = SdkUtils.toJSONString(request);
        try {
            String resultJson = SdkUtils.doPostJson2(this.serverUrl, requestJson);
            String[] s = resultJson.split(FieldConstants.REQ_AUTHORIZATION + "===");
            if (s.length == 1 || StringUtils.isBlank(s[1])) {
                this.token = null;
            } else {
                this.token = s[1];
            }
            return new ResponseContent(number, s[0]);
        } catch (IOException var7) {
            return new ResponseContent(number);
        }
    }
}
